<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { get, post } from '@/utils/service'
import { BOOKING_TIMES, SERVICE_MOBILEPHONE, VUE_APP_BASE_API } from '@/utils/baseConfig'
import { showNotify } from 'vant' // 可选：根据你的UI库引入提示组件，如 Element-UI, Vant 等
import router from '@/router'
function onClickLeft() {
  window.history.back()
}
const nowDate = new Date()
const minDate = new Date(nowDate.getFullYear(), nowDate.getMonth(), nowDate.getDate() + 1)
const maxDate = new Date(nowDate.getFullYear(), nowDate.getMonth(), nowDate.getDate() + 14)
const routers = useRouter()
const member = ref({})
const custName = ref('')
const mobilePhone = ref('')
const loadingStatus = ref(false)
const showSignDialog = ref(false)
const entepriseColumns = ref([])
const brandColumns = ref([])
const note = ref('')
//门店选择器
const resultEnterpriseName = ref('')
const enterpriseValue = ref([])
const showEnterprisePicker = ref(false)
const online = ref({})
queryCarMasterWechat()
function queryCarMasterWechat() {
  // 异步更新数据
  // setTimeout 仅做示例，真实场景中一般为 ajax 请求
  get('/memberWechatNew/queryMemberWehcat', {})
    .then((res) => {
      if (res.code === 0) {
        const memberInfo = res.data
        member.value = memberInfo
        custName.value = memberInfo.name
        mobilePhone.value = memberInfo.mobilePhone
      } else {
        showNotify({
          type: 'danger',
          message: '获取会员信息失败',
          color: '#FFF',
          background: '#797979',
        })
      }
    })
    .catch((err) => {
      console.log(err)
    })
}
onMounted(async () => {
  try {
    queryEnterprise()
    queryBrands()
  } catch (error) {
    console.log('onMounted error:' + error)
  }
})
function onEnterpriseConfirm(selectedValues: {}) {
  resultEnterpriseName.value = selectedValues.selectedOptions[0].text
  enterpriseValue.value.push(selectedValues.selectedOptions[0].value)
  showEnterprisePicker.value = false
}

//品牌选择器
const brandName = ref('')
const brandValue = ref([])
const showBrandPicker = ref(false)

function onBrandConfirm(selectedValues: {}) {
  brandName.value = selectedValues.selectedOptions[0].text
  brandValue.value.push(selectedValues.selectedOptions[0].value)
  showBrandPicker.value = false
  carSeriyName.value = ''
  carSeriyColumns.value = []
  queryCarSeriys(selectedValues.selectedOptions[0].value)
}
//品牌选择器
const carSeriyName = ref('')
const carSeriyValue = ref([])
const showCarSeriyPicker = ref(false)
const carSeriyColumns = ref([])

function onCarSeriyConfirm(selectedValues: {}) {
  carSeriyName.value = selectedValues.selectedOptions[0].text
  carSeriyValue.value.push(selectedValues.selectedOptions[0].value)
  showCarSeriyPicker.value = false
}
// 校验函数返回 true 表示校验通过，false 表示不通过

function onFailed(errorInfo: Error | string) {
  console.log('failed', errorInfo)
}
function submitFrm(values: object) {
  console.log('submit', values)
  try {
    online.value.name = custName.value
    online.value.mobilePhone = mobilePhone.value
    online.value.acceptEnterpriseId = enterpriseValue.value[0] || ''
    online.value.acceptEnterpriseName = values.acceptEnterpriseName
    online.value.brandId = brandValue.value[0] || ''
    online.value.brandName = values.brandName
    online.value.carSeriyId = carSeriyValue.value[0] || ''
    online.value.carSeriyName = values.carSeriyName
    online.value.bookingDate = onlineDate.value
    online.value.bookingTime = onlineTime.value
    online.value.bookingDes = note.value
    showSignDialog.value = true
  } catch (error) {
    console.log('submit error:' + error)
    loadingStatus.value = false // 隐藏加载状态
    showNotify({ type: 'danger', message: error, color: '#FFF', background: '#797979' })
  } finally {
    loadingStatus.value = false // 隐藏加载状态
  }
}
function saveFrm() {
  const onlineModel = online.value
  loadingStatus.value = true // 显示加载状态
  try {
    post('/onlineBookingWechatNew/saveTryCarWechat', onlineModel).then((res) => {
      if (res.code === 0) {
        let previousUrl = routers.options.history.state?.back || window.location.href
        console.log('上一个链接是:', previousUrl)
        let mesg = ''
        if (previousUrl == null || previousUrl.length <= 0) {
          previousUrl = '/'
          mesg = '即将跳转首页...'
        }
        showNotify({ type: 'success', message: res.msg + mesg, duration: 3000 })
        setTimeout(() => {
          routers.push(previousUrl)
        }, 1000)
      } else {
        showNotify({ type: 'danger', message: res.msg, color: '#FFF', background: '#797979' })
      }
    })
  } catch (error) {
    console.log('submit error:' + error)
    loadingStatus.value = false // 隐藏加载状态
    showNotify({ type: 'danger', message: error, color: '#FFF', background: '#797979' })
  } finally {
    loadingStatus.value = false // 隐藏加载状态
  }
}
function queryEnterprise() {
  get('/enterpriseWechatNew/queryWechatSelect', {}).then((res) => {
    entepriseColumns.value = []
    if (res.code === 0) {
      const data = res.data
      entepriseColumns.value.push(data)
    }
  })
}
function queryBrands() {
  get('/brandWechatNew/queryWechatSelect', {}).then((res) => {
    if (res.code === 0) {
      const data = res.data
      brandColumns.value.push(data)
    } else {
      brandColumns.value.push([])
    }
  })
}
function queryCarSeriys(brandId) {
  get('/carSeriyWechatNew/queryWechatList', { brandId: brandId }).then((res) => {
    if (res.code === 0) {
      const data = res.data
      carSeriyColumns.value.push(data)
    } else {
      carSeriyColumns.value.push([])
    }
  })
}
function phoneValidator() {
  return /^1\d{10}$/.test(mobilePhone.value)
}
function nameValidator() {
  return /^[\u4e00-\u9fa5]{2,10}$/.test(custName.value)
}
const onlineDate = ref('')
const showCalendar = ref(false)
function onConfirm(date: Date) {
  const dateDay = date.getDate()
  let day = ''
  if (dateDay > 9) {
    day = dateDay + ''
  } else {
    day = '0' + dateDay
  }
  onlineDate.value = `${date.getFullYear()}-${date.getMonth() + 1}-${day}`
  showCalendar.value = false
}

const onlineTime = ref('')
const pickerValue = ref([])
const showPicker = ref(false)

function onConfirmTime({ selectedValues, selectedOptions }) {
  onlineTime.value = selectedOptions[0]?.text
  pickerValue.value = selectedValues
  showPicker.value = false
}
function viewHistoryOnline() {
  router.push('/myOnline')
}
</script>
<template>
  <van-nav-bar title="预约试驾" left-text="返回" left-arrow @click-left="onClickLeft" />
  <div class="mainContent">
    <div style="margin: auto 0; text-align: center; padding: 20px 20px; width: 100%">
      <van-image
        width="5rem"
        height="5rem"
        :src="VUE_APP_BASE_API + '/images/vue/tryCar.png'"
        position="center"
      />
    </div>
    <van-form @failed="onFailed" @submit="submitFrm">
      <van-cell-group inset>
        <!-- 通过 pattern 进行正则校验 -->
        <van-field
          v-model="custName"
          required="true"
          label="姓名"
          name="custName"
          placeholder="客户姓名"
          :value="custName"
          :rules="[
            { required: true, message: '请填写姓名' },
            { validator: nameValidator, message: '请输入购车客户姓名,2-10个中文字符' },
          ]"
        />
        <van-field
          v-model="mobilePhone"
          label="联系电话"
          required="true"
          name="mobilePhone"
          placeholder="客户联系电话"
          type="tel"
          :rules="[
            { required: true, message: '请填写手机号码' },
            { validator: phoneValidator, message: '请输入正确的手机号格式', trigger: 'onBlur' },
          ]"
        />
        <van-field
          v-model="onlineDate"
          required="true"
          is-link
          readonly
          name="onlineDate"
          label="预约日期"
          placeholder="点击选择日期"
          @click="showCalendar = true"
          :rules="[
            { required: true, message: '请选择预约日期' },
            { validator: phoneValidator, message: '请输入正确的手机号格式', trigger: 'onBlur' },
          ]"
        />
        <van-calendar
          v-model:show="showCalendar"
          @confirm="onConfirm"
          :min-date="minDate"
          :max-date="maxDate"
        />
        <van-field
          v-model="onlineTime"
          is-link
          readonly
          required="true"
          name="onlineTime"
          label="预约时段"
          placeholder="点击选择预约时段"
          @click="showPicker = true"
          :rules="[{ required: true, message: '请选择预约时段' }]"
        />
        <van-popup v-model:show="showPicker" destroy-on-close position="bottom">
          <van-picker
            :columns="BOOKING_TIMES"
            :model-value="pickerValue"
            @confirm="onConfirmTime"
            @cancel="showPicker = false"
          />
        </van-popup>
        <van-field
          v-model="resultEnterpriseName"
          is-link
          readonly
          name="acceptEnterpriseName"
          label="门店"
          placeholder="点击选择门店"
          required="true"
          @click="showEnterprisePicker = true"
          :rules="[{ required: true, message: '请选择门店' }]"
        />
        <van-popup :show="showEnterprisePicker" destroy-on-close position="bottom">
          <van-picker
            :columns="entepriseColumns"
            :model-value="enterpriseValue"
            @confirm="onEnterpriseConfirm"
            @cancel="showEnterprisePicker = false"
          />
        </van-popup>
        <van-field
          v-model="brandName"
          is-link
          readonly
          name="brandName"
          label="品牌"
          placeholder="点击选择品牌"
          @click="showBrandPicker = true"
          required="true"
          :rules="[{ required: true, message: '请选择品牌' }]"
        />
        <van-popup v-model:show="showBrandPicker" destroy-on-close position="bottom">
          <van-picker
            :columns="brandColumns"
            :model-value="brandValue"
            @confirm="onBrandConfirm"
            @cancel="showBrandPicker = false"
          />
        </van-popup>
        <van-field
          v-model="carSeriyName"
          is-link
          readonly
          name="carSeriyName"
          label="车系"
          placeholder="点击选择车系"
          required="true"
          @click="showCarSeriyPicker = true"
          :rules="[{ required: true, message: '请选择车系' }]"
        />
        <van-popup v-model:show="showCarSeriyPicker" destroy-on-close position="bottom">
          <van-picker
            :columns="carSeriyColumns"
            :model-value="carSeriyValue"
            @confirm="onCarSeriyConfirm"
            @cancel="showCarSeriyPicker = false"
          />
        </van-popup>
      </van-cell-group>
      <van-cell-group inset>
        <van-field
          v-model="note"
          rows="2"
          autosize
          label="备注"
          type="textarea"
          name="note"
          maxlength="120"
          placeholder="请输入备注"
          show-word-limit
        />
      </van-cell-group>
      <div style="margin: 16px">
        <van-button
          round
          block
          type="primary"
          loading-type="spinner"
          loading-text="提交中..."
          native-type="submit"
        >
          提交
        </van-button>
      </div>
    </van-form>
  </div>
  <!--保存钱确认-->
  <van-popup
    closeable
    v-model:show="showSignDialog"
    position="bottom"
    round
    :style="{ height: '72%' }"
  >
    <div>
      <h3 class="memberInfoPopTitle">预约信息确认</h3>
    </div>
    <div class="mainContent" style="padding: 30px 30px">
      <van-cell-group>
        <van-cell title="姓名" :value="online.name" />
        <van-cell title="联系电话" :value="online.mobilePhone" />
        <van-cell title="预约日期" :value="online.bookingDate" value-class="price" />
        <van-cell title="预约时段" :value="online.bookingTime" />
        <van-cell title="门店" :value="online.acceptEnterpriseName || '无'" />
        <van-cell title="品牌" :value="online.brandName || '无'" />
        <van-cell title="车系" :value="online.carSeriyName || '无'" />
      </van-cell-group>
      <van-cell-group border="false">
        <p style="line-height: 200%">备注</p>
        <div class="" style="font-size: 14px; color: var(--van-text-color-2)">
          {{ online.bookingDes || '无' }}
        </div>
      </van-cell-group>
    </div>
    <div style="margin: 16px">
      <van-button
        round
        block
        type="primary"
        :loading="loadingStatus"
        loading-type="spinner"
        loading-text="提交中..."
        native-type="submit"
        @click="saveFrm"
      >
        提交
      </van-button>
    </div>
  </van-popup>
  <van-divider :style="{ color: '#1989fa', borderColor: '#1989fa', padding: '0 16px' }">
    温馨提示
  </van-divider>

  <div class="mainContent" style="margin-bottom: 32px">
    <p style="font-size: 14px">
      若您在预约过程中有任何为题请拨打：<a
        :href="'tel:' + SERVICE_MOBILEPHONE"
        style="color: var(--main-color)"
        >{{ SERVICE_MOBILEPHONE }}</a
      >
    </p>
    <p style="font-size: 14px">
      历史预约记录：<a style="color: var(--main-color)" @click="viewHistoryOnline">点击查看</a>
    </p>
  </div>
</template>

<style></style>
